//
//  ViewController+location.swift
//  WZApp
//
//  Created by evol on 2018/7/31.
//  Copyright © 2018年 evol. All rights reserved.
//

import UIKit

extension ViewController: AMapLocationManagerDelegate {

    func setUpLocation() -> Void {
        locationManager.delegate = self
        locationManager.startUpdatingLocation()
        
        _ = ELLocationManager.share
        
    }
    
    func amapLocationManager(_ manager: AMapLocationManager!, didUpdate location: CLLocation!) {
        if location.horizontalAccuracy > 100 {
            print("定位精度不够")
            return
        }
        if inWuzhen(location.coordinate) {
            currentLocation = location.coordinate
        }else{
            currentLocation.latitude = 30.748090
            currentLocation.longitude = 120.486694
        }
    }
    
    func inWuzhen(_ coordinate: CLLocationCoordinate2D) -> Bool {
        let minX:CLLocationDegrees = 30.7451629231771;
        let maxX:CLLocationDegrees = 30.7537699110243;
        let minY:CLLocationDegrees = 120.475905653212;
        let maxY:CLLocationDegrees = 120.491067599826;
        if coordinate.latitude < maxX && coordinate.latitude > minX && coordinate.longitude < maxY && coordinate.longitude > minY {
            return true
        }
        return false
    }
    
    func navigateRoute(_ model:ELTagModel) -> Void {
        let group = DispatchGroup()
        var startId: NSInteger?
        var endId: NSInteger?
        group.enter()
        ELAppService.loadNearestRoutePoint(CGPoint(x: (model.gis_x?.floatValue)!, y: (model.gis_y?.floatValue)!)).subscribe(onNext:{result in
            endId = result
            group.leave()
        }).disposed(by: self.disposeBag)
        
        group.enter()
        ELAppService.loadNearestRoutePoint(CGPoint(x: self.currentLocation.latitude, y: self.currentLocation.longitude)).subscribe(onNext:{result in
            startId = result
            group.leave()
        }).disposed(by: self.disposeBag)
        
        group.notify(queue: DispatchQueue.main) {
            if (startId != nil) && (endId != nil) {
                ELAppService.loadRouteLines(startId: startId!, endId: endId!).subscribe(onNext: {result in
                    print( result )
                }).disposed(by: self.disposeBag)
            }
        }
    }
}
